// 导入 express 和数据库模块
const express = require('express');
const router = express.Router();
const db = require('../db');
const jwt = require('jsonwebtoken')
// 登录接口
router.post('/adminLogin', (req, res) => {
    const { username, password } = req.body;

    // 查询数据库中是否存在匹配的用户
    const query = 'SELECT * FROM admin WHERE username = ? AND password = ?';
    db.query(query, [username, password], (err, results) => {
        if (err) {
            console.error('查询数据库出错:', err);
            return res.status(500).json({ message: '服务器错误，请稍后重试', status: 500 });
        }

        if (results.length > 0) {
            console.log(results[0]);
            const role = results[0].role;
            // 登录成功，返回 adminId
            if (results[0].adminId){
                const adminId = results[0].adminId;
                // 生成Token
                const tokenStr = jwt.sign({
                        role: role,
                        id: adminId,
                    }, 'kiorry',
                    {expiresIn: '5h'}
                );
                res.json({ message: '登录成功', status: 200, adminId, role, token:'Bearer ' + tokenStr })
            }else if (results[0].teacherId){
                const teacherId = results[0].teacherId;
                // 生成Token
                const tokenStr = jwt.sign({
                        role: role,
                        id: teacherId,
                    }, 'kiorry',
                    {expiresIn: '5h'}
                );
                res.json({ message: '登录成功', status: 200, teacherId, role, token:'Bearer ' + tokenStr })
            }
        } else {
            // 登录失败
            res.json({ message: '账号或密码错误', status: 404 });
        }
    });
});

// 将路由对象共享出去
module.exports = router
